Skip to content

第一个 EF Core 应用

创建项目

sh
$ dotnet new console -o EFCoreSamples

安装 Entity Framework Core

sh
$ cd SqliteSamples
$ dotnet add package Microsoft.EntityFrameworkCore.Sqlite

用法

创建模型

c#
using Microsoft.EntityFrameworkCore;

namespace EFCoreSamples;

// 数据库上下文类,继承自Entity Framework Core的DbContext
// 负责管理与数据库的交互,包含数据模型和数据库配置
public class BloggingContext : DbContext
{
    // DbSet属性表示数据库中的表,每个DbSet对应一个数据模型类
    public DbSet<Blog> Blogs { get; set; }  // Blogs表,对应Blog实体
    public DbSet<Post> Posts { get; set; }  // Posts表,对应Post实体

    // 数据库文件路径
    public string DbPath { get; }

    // 构造函数:初始化数据库上下文
    public BloggingContext()
    {
        // 组合完整数据库文件路径
        DbPath = Path.Join(@"D:\sqlite", "blogging.db");
    }

    // 配置DbContext选项,指定使用SQLite数据库
    protected override void OnConfiguring(DbContextOptionsBuilder options)
        => options.UseSqlite($"Data Source={DbPath}");
}

// 博客实体类
public class Blog
{
    public int BlogId { get; set; }       // 主键(EF Core默认将Id或[类名]Id识别为主键)
    public string Url { get; set; }       // 博客网址

    // 导航属性:表示博客包含的多篇文章(一对多关系)
    // new() 初始化确保列表不为null
    public List<Post> Posts { get; } = new();
}

// 文章实体类
public class Post
{
    public int PostId { get; set; }       // 主键
    public string Title { get; set; }     // 文章标题
    public string Content { get; set; }   // 文章内容

    // 外键:关联的博客ID
    public int BlogId { get; set; }
    // 导航属性:所属博客(多对一关系)
    public Blog Blog { get; set; }
}

创建数据库(可选)

sh
$ dotnet tool install --global dotnet-ef
$ dotnet add package Microsoft.EntityFrameworkCore.Design
$ dotnet ef migrations add InitialCreate
$ dotnet ef database update

创建、读取、更新 & 删除

c#
using System;
using System.Linq;
using EFCoreSamples;
using Microsoft.EntityFrameworkCore;

// 使用DbContext上下文,using确保资源正确释放
using var db = new BloggingContext();

// 注意:此示例需要先创建数据库
Console.WriteLine($"Database path: {db.DbPath}.");

// 新增(Create)
Console.WriteLine("Inserting a new blog");
// 创建新的Blog实体实例
db.Add(new Blog { Url = "http://blogs.msdn.com/adonet" });
// 异步保存更改到数据库
await db.SaveChangesAsync();

// 查询(Read)
Console.WriteLine("Querying for a blog");
// 按BlogId排序后获取第一个博客
// 使用FirstAsync异步获取第一条记录
var blog = await db.Blogs
    .OrderBy(b => b.BlogId)
    .FirstAsync();

// 更新(Update)
Console.WriteLine("Updating the blog and adding a post");
// 修改博客属性
blog.Url = "https://devblogs.microsoft.com/dotnet";
// 向博客添加新帖子(一对多关系)
blog.Posts.Add(
    new Post { 
        Title = "Hello World", 
        Content = "I wrote an app using EF Core!" 
    });
// 异步保存更改(同时更新博客URL和新增帖子)
await db.SaveChangesAsync();

// 删除(Delete)
Console.WriteLine("Delete the blog");
// 标记博客实体为删除状态
db.Remove(blog);
// 异步执行数据库删除操作
await db.SaveChangesAsync();

测试

sh
$ dotnet run
Database path: D:\sqlite\blogging.db.
Inserting a new blog
Querying for a blog
Updating the blog and adding a post
Delete the blog

Last updated:

Released under the MIT License.